<?php

/**
 * Author：晴天 QQ：1186258278
 * Creation：2020/7/20 18:59
 * Filename：main.php
 */


include("./includes/fun.global.php");
@header('Content-Type: application/json; charset=UTF-8');
$DB = \Medoo\DB\SQL::DB();
$User = login_data::user_data();
include_once(SYSTEM_ROOT . "extend/GoodsCart.php");

use extend\GoodsImage;
use extend\UserConf;
use lib\AppStore\AppList;
use lib\Hook\Hook;
use lib\supply\Order;
use Medoo\DB\SQL;

switch ($_QET['act']) {
    case 'banner':
        $Data = HomecachingVerify('banner', ['Home']);
        if ($Data == false) {
            $banner = explode('|', $conf['banner']);
            $Data = [];
            foreach ($banner as $v) {
                $is = explode('*', $v);
                $Data[] = [
                    'image' => ImageUrl($is[0]),
                    'url' => htmlspecialchars_decode($is[1]),
                ];
            }
            HomecachingAdd('banner', ['Home'], $Data);
        }
        dier([
            'code' => 1,
            'msg' => '获取成功',
            'title' => ($conf['title'] == '' ? $conf['sitename'] : $conf['sitename'] . '-' . $conf['title']),
            'data' => $Data,
        ]);
        break;
    case 'Service': //客服数据
        QR_Code(2, 'http://wpa.qq.com/msgrd?v=3&uin=' . $conf['kfqq'] . '&site=qq&menu=yes', 5, 0, SYSTEM_ROOT . 'extend/log/ShopImage/' . md5($conf['kfqq']) . '.png');
        $Image = is_https(false) . href() . '/includes/extend/log/ShopImage/' . md5($conf['kfqq']) . '.png';
        dier([
            'code' => 1,
            'msg' => '数据获取成功',
            'qq' => $conf['kfqq'],
            'image' => ($conf['ServiceImage'] == '' ? $Image : ImageUrl($conf['ServiceImage'])),
            'url' => ($conf['YzfSign'] == '' ? -1 : 'https://yzf.qq.com/xv/web/static/chat/index.html?sign=' . $conf['YzfSign']),
            'tips' => htmlspecialchars_decode($conf['ServiceTips']),
            'GroupUrl' => ($conf['Communication'] == '' ? -1 : htmlspecialchars_decode($conf['Communication'])),
        ]);
        break;
    case 'ArticleList': //文章列表
        test(['page|e']);

        $Data = HomecachingVerify('ArticleList', [$_QET['page'], $_QET['search']]);
        if ($Data != false) {
            if (!empty($_QET['search'])) {
                Hook::execute('ArticleSeek', [
                    'uid' => ($User == false ? -1 : $User['id']),
                    'search' => $_QET['search']
                ]);
            } else {
                Hook::execute('ArticleList', [
                    'uid' => ($User == false ? -1 : $User['id'])
                ]);
            }
            dier([
                'code' => 1,
                'msg' => '数据获取成功',
                'data' => $Data
            ]);
        }

        $LIMIT = (empty($conf['HomeLimit']) ? 6 : $conf['HomeLimit']);
        $Page = ($_QET['page'] - 1) * $LIMIT;

        $SQL = [
            'LIMIT' => [$Page, $LIMIT],
            'ORDER' => [
                'id' => 'DESC'
            ]
        ];

        if (!empty($_QET['search'])) {
            $SQL = array_merge($SQL, [
                'title[~]' => $_QET['search']
            ]);
            Hook::execute('ArticleSeek', [
                'uid' => ($User == false ? -1 : $User['id']),
                'search' => $_QET['search']
            ]);
        } else {
            Hook::execute('ArticleList', [
                'uid' => ($User == false ? -1 : $User['id'])
            ]);
        }

        $Res = $DB->select('notice', '*', $SQL);

        if ($Res) {
            $Data = [];
            foreach ($Res as $v) {
                $Data[] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                    'content' => htmlspecialchars_decode(base64_decode($v['content'])),
                    'image' => ImageUrl($v['image']),
                    'count' => count(explode('|', $v['browse'])),
                    'addtime' => $v['date']
                ];
            }
            HomecachingAdd('ArticleList', [$_QET['page'], $_QET['search']], $Data);
            dier([
                'code' => 1,
                'msg' => '数据获取成功',
                'data' => $Data
            ]);
        } else {
            dies(-2, '文章列表获取失败');
        }
        break;
    case 'class': //取出分类列表
        test(['num|i']);
        $Data = HomecachingVerify($_QET['act'] . $_QET['num'], $User);
        if ($Data == false) {
            $Res = $DB->select('class', '*', [
                'ORDER' => [
                    'sort' => 'DESC'
                ],
                'state' => 1,
                'LIMIT' => $_QET['num']
            ]);
            $Data = [];
            foreach ($Res as $v) {
                $v['image'] = ImageUrl($v['image']);
                $v['count'] = $DB->count('goods', ['cid' => $v['cid'], 'state' => 1]);
                $Data[] = $v;
            }
            HomecachingAdd($_QET['act'] . $_QET['num'], $User, $Data);
        }
        dier([
            'code' => 1,
            'msg' => '商品分类数据获取成功',
            'data' => $Data
        ]);

        break;
    case 'GoodsSeek': //取出搜索列表
        test(['keyword|i', 'page|e'], '请将搜索内容填写完整');

        $GoodsHide = UserConf::GoodsHide(); //取出不显示商品ID

        $Data = HomecachingVerify($_QET['act'], [$_QET['keyword'], $_QET['page']]);
        if ($Data == false) {
            if ($_QET['page'] == -1) {
                $SQL = [
                    'ORDER' => [
                        'sort' => 'DESC'
                    ],
                    'state' => 1,
                    'name[~]' => $_QET['keyword']
                ];
            } else {
                $LIMIT = (empty($conf['HomeLimit']) ? 6 : $conf['HomeLimit']);
                $Page = ($_QET['page'] - 1) * $LIMIT;

                $SQL = [
                    'ORDER' => [
                        'sort' => 'DESC'
                    ],
                    'state' => 1,
                    'name[~]' => $_QET['keyword'], 'LIMIT' => [$Page, $LIMIT]
                ];
            }

            if (count($GoodsHide) >= 1) {
                $SQL = array_merge($SQL, [
                    'gid[!]' => $GoodsHide
                ]);
            }

            $Res = $DB->select('goods', [
                'gid', 'cid', 'name', 'image', 'money', 'profits', 'custom', 'freight', 'method',
                'quantity', 'quota', 'sqid', 'label', 'specification', 'specification_set', 'specification_sku',
            ], $SQL);
            $Data = [];
            foreach ($Res as $res) {
                if ($res['specification'] == 2) {
                    $SpRule = RlueAnalysis($res['specification_set'], $res, 1, true);
                    if ($SpRule == -1) {
                        $res['DataRule'] = -1;
                        $price = price::price_uid(($User == false ? -1 : $User['grade']), $res['profits'], $res['money'], $res['custom'], UserConf::GoodsPrice($res['gid']));
                        $Coun = $DB->sum('buylog', 'num', [
                            'gid' => $res['gid'],
                            'date[>]' => $times
                        ]);
                        $res['quota'] = $res['quota'] - $Coun;
                        $res['level'] = $price['level'];
                    } else {
                        $SkuData = [
                            'data' => $SpRule,
                        ];
                        $DataRule = $SkuData['data']['Parameter'][$Index];
                        $res['quantity'] = $SkuData['data']['Quantity']['max'];
                        $res['quota'] = $SkuData['data']['Inventory']['max'];
                        $res['level'] = $SkuData['data']['level'];
                        $price = [
                            'price' => $SkuData['data']['Price']['min'],
                            'points' => $SkuData['data']['Points']['min'],
                            'level' => $DataRule['level'],
                        ];
                        $res['DataRule'] = [
                            'Price' => $SkuData['data']['Price'],
                            'Points' => $SkuData['data']['Points'],
                            'Inventory' => $SkuData['data']['Inventory'],
                            'Quantity' => $SkuData['data']['Quantity'],
                        ];
                    }
                } else {
                    $res['DataRule'] = -1;
                    $price = price::price_uid(($User == false ? -1 : $User['grade']), $res['profits'], $res['money'], $res['custom'], UserConf::GoodsPrice($res['gid']));
                    $Coun = $DB->sum('buylog', 'num', [
                        'gid' => $res['gid'],
                        'date[>]' => $times
                    ]);
                    $res['quota'] = $res['quota'] - $Coun;
                    $res['level'] = $price['level'];
                }

                if ($res['sqid'] == -3) {
                    //获取卡密库存
                    $res['quota'] = $DB->count('token', [
                        "AND" => [
                            "OR" => [
                                "order[=]" => "",
                                "order" => null
                            ],
                            "gid" => $res['gid']
                        ],
                    ]);
                }

                $res['method'] = json_decode($res['method'], true);

                if (in_array(2, $res['method']) && in_array(3, $res['method'])) {
                    //支持余额+积分
                    $res['method'] = 1;
                } elseif (in_array(2, $res['method']) && !in_array(3, $res['method'])) {
                    //支持余额不支持积分
                    $res['method'] = 2;
                } elseif (!in_array(2, $res['method']) && in_array(3, $res['method'])) {
                    //不支持余额支持积分
                    $res['method'] = 3;
                } else {
                    //其他
                    $res['method'] = 2;
                }

                if ($price['price'] <= 0.01 && $price['price'] <> 0) {
                    $price['price'] = 0.01;
                }
                $res['price'] = round($price['price'], 2);
                $res['points'] = round($price['points'], 0);
                $res['level'] = $price['level'];

                if ($res['label'] == '') {
                    $res['label'] = explode('|', $conf['DefaultLabel']);
                } else {
                    $res['label'] = explode('|', $res['label']);
                    if (count($res['label']) == 0) {
                        $res['label'] = explode('|', $conf['DefaultLabel']);
                    }
                }

                if (count($res['label']) == 0) {
                    $res['label'] = ['官方'];
                }
                $Label = [];
                foreach ($res['label'] as $v) {
                    $v = explode(',', $v);
                    $Label[] = [
                        'name' => $v[0],
                        'color' => (empty($v[1]) ? 'red' : $v[1])
                    ];
                }
                $res['label'] = $Label;

                switch ($res['sqid']) {
                    case -1: //自营
                        $res['state'] = 1;
                        break;
                    case -2: //API
                        $res['state'] = 2;
                        break;
                    case -3: //发卡
                        $res['state'] = 3;
                        break;
                    default: //对接
                        $res['state'] = 4;
                        break;
                }

                $res['currency'] = $conf['currency'];

                unset($res['profits'], $res['money'], $res['sqid'], $res['specification_set'], $res['specification_sku'], $res['custom']);

                $res['image'] = ImageUrl($res['image']);

                if (empty($_SESSION['GIDSALES_' . $res['gid']])) {
                    $LSALES = $conf['SalesSum'] + round(($conf['SalesSum'] * (rand(1, 50) / 100)), 0);
                    $_SESSION['GIDSALES_' . $res['gid']] = $LSALES;
                } else {
                    $LSALES = $_SESSION['GIDSALES_' . $res['gid']];
                }

                $res['sales'] = $DB->sum('order', 'num', ['gid' => $res['gid']]) + $LSALES;

                $Data[] = $res;
            }

            HomecachingAdd($_QET['act'], [$_QET['keyword'], $_QET['page']], $Data);
        }
        if ($_QET['page'] > 1 && count($Data) == 0) {
            dies(-2, '没有更多带有[' . $_QET['keyword'] . ']关键词的商品了！');
        }
        if (count($Data) == 0) {
            dies(-3, '没有找到带有[' . $_QET['keyword'] . ']关键词的商品！');
        }

        $Count = $DB->count('goods', [
            'name[~]' => $_QET['keyword'],
            'state' => 1
        ]);

        Hook::execute('GoodsSeek', [
            'name' => $_QET['keyword'],
            'uid' => ($User == false ? -1 : $User['id'])
        ]);

        dier([
            'code' => 1,
            'msg' => '搜索成功！',
            'data' => $Data,
            'tips' => '共找到' . $Count . '个带有[' . $_QET['keyword'] . ']关键词的宝贝！',
            'limit' => $LIMIT - 0
        ]);
        break;
    case 'GoodsList': //取出分类下的商品列表

        $GoodsHide = UserConf::GoodsHide(); //取出不显示商品ID

        test(['cid|e', 'page|e']);
        Hook::execute('GoodsList', [($User == false ? -1 : $User['id']), 'cid' => $_QET['cid']]);

        $Data = HomecachingVerify($_QET['act'] . $_QET['cid'] . $_QET['page'], $User);

        if ($Data == false) {
            if ($_QET['page'] == -1) {
                $SQL = [
                    'ORDER' => [
                        'sort' => 'DESC'
                    ],
                    'state' => 1
                ];
            } else {
                $LIMIT = (empty($conf['HomeLimit']) ? 6 : $conf['HomeLimit']);
                $Page = ($_QET['page'] - 1) * $LIMIT;

                $SQL = [
                    'ORDER' => [
                        'sort' => 'DESC'
                    ],
                    'state' => 1, 'LIMIT' => [$Page, $LIMIT]
                ];
            }

            if ((int)$_QET['cid'] >= 1) {
                $SQL = array_merge($SQL, [
                    'cid' => (int)$_QET['cid']
                ]);
            }

            if (count($GoodsHide) >= 1) {
                $SQL = array_merge($SQL, [
                    'gid[!]' => $GoodsHide
                ]);
            }

            $Res = $DB->select('goods', [
                'gid', 'cid', 'name', 'image', 'money', 'profits', 'custom', 'freight', 'method',
                'quantity', 'quota', 'sqid', 'label', 'specification', 'specification_set', 'specification_sku',
            ], $SQL);
            $Data = [];
            foreach ($Res as $res) {
                if ($res['specification'] == 2) {
                    $SpRule = RlueAnalysis($res['specification_set'], $res, 1, true);
                    if ($SpRule == -1) {
                        $res['DataRule'] = -1;
                        $price = price::price_uid(($User == false ? -1 : $User['grade']), $res['profits'], $res['money'], $res['custom'], UserConf::GoodsPrice($res['gid']));
                        $Coun = $DB->sum('buylog', 'num', [
                            'gid' => $res['gid'],
                            'date[>]' => $times
                        ]);
                        $res['quota'] = $res['quota'] - $Coun;
                        $res['level'] = $price['level'];
                    } else {
                        $SkuData = [
                            'data' => $SpRule,
                        ];
                        $DataRule = $SkuData['data']['Parameter'][$Index];
                        $res['quantity'] = $SkuData['data']['Quantity']['max'];
                        $res['quota'] = $SkuData['data']['Inventory']['max'];
                        $res['level'] = $SkuData['data']['level'];
                        $price = [
                            'price' => $SkuData['data']['Price']['min'],
                            'points' => $SkuData['data']['Points']['min'],
                            'level' => $DataRule['level'],
                        ];
                        $res['DataRule'] = [
                            'Price' => $SkuData['data']['Price'],
                            'Points' => $SkuData['data']['Points'],
                            'Inventory' => $SkuData['data']['Inventory'],
                            'Quantity' => $SkuData['data']['Quantity'],
                        ];
                    }
                } else {
                    $res['DataRule'] = -1;
                    $price = price::price_uid(($User == false ? -1 : $User['grade']), $res['profits'], $res['money'], $res['custom'], UserConf::GoodsPrice($res['gid']));
                    $Coun = $DB->sum('buylog', 'num', [
                        'gid' => $res['gid'],
                        'date[>]' => $times
                    ]);
                    $res['quota'] = $res['quota'] - $Coun;
                    $res['level'] = $price['level'];
                }

                if ($res['sqid'] == -3) {
                    //获取卡密库存
                    $res['quota'] = $DB->count('token', [
                        "AND" => [
                            "OR" => [
                                "order[=]" => "",
                                "order" => null
                            ],
                            "gid" => $res['gid']
                        ],
                    ]);
                }

                $res['method'] = json_decode($res['method'], true);

                if (in_array(2, $res['method']) && in_array(3, $res['method'])) {
                    //支持余额+积分
                    $res['method'] = 1;
                } elseif (in_array(2, $res['method']) && !in_array(3, $res['method'])) {
                    //支持余额不支持积分
                    $res['method'] = 2;
                } elseif (!in_array(2, $res['method']) && in_array(3, $res['method'])) {
                    //不支持余额支持积分
                    $res['method'] = 3;
                } else {
                    //其他
                    $res['method'] = 2;
                }

                if ($price['price'] <= 0.01 && $price['price'] <> 0) {
                    $price['price'] = 0.01;
                }
                $res['price'] = round($price['price'], 2);
                $res['points'] = round($price['points'], 0);

                switch ($res['sqid']) {
                    case -1: //自营
                        $res['state'] = 1;
                        break;
                    case -2: //API
                        $res['state'] = 2;
                        break;
                    case -3: //发卡
                        $res['state'] = 3;
                        break;
                    default: //对接
                        $res['state'] = 4;
                        break;
                }

                $res['currency'] = $conf['currency'];

                unset($res['profits'], $res['money'], $res['sqid'], $res['specification_set'], $res['specification_sku'], $res['custom']);

                $res['image'] = ImageUrl($res['image']);

                if (empty($_SESSION['GIDSALES_' . $res['gid']])) {
                    $LSALES = $conf['SalesSum'] + round(($conf['SalesSum'] * (rand(1, 50) / 100)), 0);
                    $_SESSION['GIDSALES_' . $res['gid']] = $LSALES;
                } else {
                    $LSALES = $_SESSION['GIDSALES_' . $res['gid']];
                }

                if ($res['label'] == '') {
                    $res['label'] = explode('|', $conf['DefaultLabel']);
                } else {
                    $res['label'] = explode('|', $res['label']);
                    if (count($res['label']) == 0) {
                        $res['label'] = explode('|', $conf['DefaultLabel']);
                    }
                }

                if (count($res['label']) == 0) {
                    $res['label'] = ['官方'];
                }
                $Label = [];
                foreach ($res['label'] as $v) {
                    $v = explode(',', $v);
                    $Label[] = [
                        'name' => $v[0],
                        'color' => (empty($v[1]) ? 'red' : $v[1])
                    ];
                }
                $res['label'] = $Label;

                $res['sales'] = $DB->sum('order', 'num', ['gid' => $res['gid']]) + $LSALES;

                $res['specification'] = $res['specification'] - 0;

                $Data[] = $res;
            }

            HomecachingAdd($_QET['act'] . $_QET['cid'] . $_QET['page'], $User, $Data);
        }

        if ((int)$_QET['cid'] >= 1) {
            $Cis = $DB->get('class', '*', ['cid' => (int)$_QET['cid'], 'state' => 1]);
            if (!$Cis) {
                dies(-2, '当前所选分类不存在！');
            }
        }

        dier([
            'code' => 1,
            'msg' => '商品列表获取成功',
            'data' => $Data,
            'CidArr' => ((int)$_QET['cid'] >= 1 ? $Cis : []),
        ]);
        break;
    case 'inform': //取出系统公告+导航+app下载点

        $navigationArr = [];
        foreach (explode('|', $conf['navigation']) as $value) {
            $arr = explode(',', $value);
            $navigationArr[] = [
                'name' => $arr[0],
                'url' => htmlspecialchars_decode($arr[1])
            ];
        }

        dier([
            'code' => 1,
            'msg' => '获取成功',
            'data' => [
                'NoticeTop' => $conf['notice_top'], //首页顶部
                'PopupNotice' => $conf['PopupNotice'], //弹窗
                'NoticeBottom' => $conf['notice_bottom'], //底部
                'NoticeCheck' => $conf['notice_check'], //查单
                'Appurl' => $conf['appurl'], //APP下载地址
                'Navigation' => $navigationArr, //自定义导航
                'UserImage' => ($User == false ? -1 : $User['image'])
            ]
        ]);
        break;
    case 'Goods': //取出商品详情
        test(['gid|e']);

        $GoodsHide = UserConf::GoodsHide(); //取出不显示商品ID
        if (in_array($_QET['gid'], $GoodsHide)) {
            dies(-1, '商品已下架！');
        }
        $Data = HomecachingVerify($_QET['act'], [$_QET['gid']]);
        if ($Data != false) {
            Hook::execute('OrderDetails', [
                'gid' => (int)$Res['gid'],
                'uid' => ($User == false ? -1 : $User['id']),
            ]);

            dier([
                'code' => 1,
                'msg' => '商品详情获取成功',
                'data' => $Data
            ]);
        }

        $Res = $DB->get('goods', '*', [
            'gid' => (int)$_QET['gid'],
            'state' => 1
        ]);

        if (!$Res) {
            dies(-1, '当前商品已下架或根本不存在！');
        }

        $Image = [
            ImageUrl($Res['image'])
        ];
        if ($Res['picture'] != '') {
            foreach (explode('|', $Res['picture']) as $v) {
                $Image = array_merge($Image, [ImageUrl($v)]);
            }
        }

        $price = price::price_uid(($User == false ? -1 : $User['grade']), $Res['profits'], $Res['money'], $Res['custom'], UserConf::GoodsPrice($Res['gid']));

        if ($Res['min'] == null || $Res['min'] == '') {
            $Res['min'] = 0;
        }
        if ($Res['max'] == null || $Res['max'] == '') {
            $Res['max'] = 0;
        }

        if ($Res['freight'] <> -1) {
            $freight = $DB->get('freight', '*', [
                'id' => $Res['freight']
            ]);
            if ($freight) {
                $Res['freight'] = $freight;
            }
        }

        if (empty($_SESSION['GIDSALES_' . $_QET['gid']])) {
            if ($conf['SalesSum'] == 0) {
                $LSALES = 0;
            } else {
                $LSALES = $conf['SalesSum'] + round(($conf['SalesSum'] * (rand(1, 50) / 100)), 0);
            }

            $_SESSION['GIDSALES_' . $_QET['gid']] = $LSALES;
        } else {
            $LSALES = $_SESSION['GIDSALES_' . $_QET['gid']];
        }

        $Input = []; //state = 1,普通输入框，2 = 接口输入框，3 = 收货地址输入框，4 = 下拉多选框 5 = 规格选择框

        if ($Res['specification'] == 2) {
            $SpRule = RlueAnalysis($Res['specification_set'], $Res, 2, true);
            $Input = [[
                'state' => 5,
                'data' => $SpRule,
                'SKU' => json_decode($Res['specification_sku'], true),
            ]];
        }

        if (!empty($Res['value']) || $Res['specification'] != 2) {
            foreach (explode('|', $Res['value']) as $value) {
                if (strstr($value, '{') && strstr($value, '}')) {
                    $value = explode('{', $value);
                    $value[1] = explode(',', getSubstr('{' . $value[1], '{', '}'));
                    $Input[] = [
                        'state' => 4,
                        'Data' => $value
                    ];
                } else {
                    $S = AppList::MatchingInput($value);
                    if ($S == false) {
                        $Input[] = [
                            'state' => 1,
                            'Data' => (empty($value) ? '备注信息' : $value)
                        ];
                    } else {
                        if ($S['type'] == 1) {
                            $Input[] = [
                                'state' => 3,
                                'Data' => $value,
                            ];
                        } elseif ($S['type'] == -1) {
                            $Input[] = [
                                'state' => 2,
                                'Data' => [
                                    $value,
                                    $S
                                ],
                            ];
                        }
                    }
                }
            }
        }

        $Res['cart_count'] = extend\GoodsCart::CartCount();
        $Res['method'] = json_decode($Res['method']);
        if (in_array(7, $Res['method'])) {
            $RS = 1;
        } else {
            $RS = -1;
        }
        if (in_array(2, $Res['method']) && in_array(3, $Res['method'])) {
            //支持余额+积分
            $Res['method'] = 1;
        } elseif (in_array(2, $Res['method']) && !in_array(3, $Res['method'])) {
            //支持余额不支持积分
            $Res['method'] = 2;
        } elseif (!in_array(2, $Res['method']) && in_array(3, $Res['method'])) {
            //不支持余额支持积分
            $Res['method'] = 3;
        } else {
            //其他
            $Res['method'] = 2;
        }

        switch ($Res['sqid']) {
            case -1: //自营
                $Res['state'] = 1;
                break;
            case -2: //API
                $Res['state'] = 2;
                break;
            case -3: //发卡
                $Res['state'] = 3;
                break;
            default: //对接
                $Res['state'] = 4;
                break;
        }

        $SQL = [
            'cid' => $Res['cid'],
            'state' => 1,
            'ORDER' => [
                'sort' => 'DESC'
            ]
        ];

        if (count($GoodsHide) >= 1) {
            $SQL = array_merge($SQL, [
                'gid[!]' => $GoodsHide
            ]);
        }

        $Push = [];
        if ($conf['SimilarRecommend'] == 1) {
            $PushArr = $DB->select('goods', [
                'image', 'gid', 'name'
            ], $SQL);
            foreach ($PushArr as $v) {
                $v['image'] = ImageUrl($v['image']);
                $Push[] = $v;
            }
        }

        if ($Res['sqid'] == -3) {
            //获取卡密库存
            $Res['count_quota'] = $Res['quota'] = $DB->count('token', [
                "AND" => [
                    "OR" => [
                        "order[=]" => "",
                        "order" => null
                    ],
                    "gid" => $Res['gid']
                ],
            ]);
        } else {
            $Coun = $DB->sum('buylog', 'num', [
                'gid' => $Res['gid'],
                'date[>]' => $times
            ]);
            $Res['count_quota'] = $Res['quota'] - $Coun;
        }

        if ($Res['label'] == '') {
            $Res['label'] = explode('|', $conf['DefaultLabel']);
        } else {
            $Res['label'] = explode('|', $Res['label']);
            if (count($Res['label']) == 0) {
                $Res['label'] = explode('|', $conf['DefaultLabel']);
            }
        }

        if (count($Res['label']) == 0) {
            $Res['label'] = ['官方'];
        }
        $Label = [];
        foreach ($Res['label'] as $v) {
            $v = explode(',', $v);
            $Label[] = [
                'name' => $v[0],
                'color' => (empty($v[1]) ? 'red' : $v[1])
            ];
        }
        $Res['label'] = $Label;

        $Prices = ($price['price'] < 0.01 && $price['price'] > 0 ? 0.01 : $price['price']);

        $Data = [
            'cid' => (int)$Res['cid'],
            'gid' => (int)$Res['gid'],
            'name' => $Res['name'],
            'image' => $Image,
            'method' => $Res['method'],
            'state' => (int)$Res['state'],
            'input' => $Input,
            'quantity' => (int)$Res['quantity'], //每份数量
            'docs' => htmlspecialchars_decode($Res['docs']),
            'alert' => htmlspecialchars_decode($Res['alert']),
            'min' => $Res['min'],
            'max' => $Res['max'],
            'currency' => $conf['currency'],
            'price' => round($Prices, 2), //售价
            'points' => round($price['points'], 0), //积分
            'level' => $price['level'], //当前等级
            'level_arr' => $price['level_arr'], //等级列表
            'freight' => $Res['freight'], //运费模板
            'cart_count' => $Res['cart_count'], //购物车商品数量
            'sales' => $DB->sum('order', 'num', ['gid' => $Res['gid']]) + $LSALES, //商品销量
            'count_quota' => $Res['count_quota'], //今日剩余份数
            'quota' => $Res['quota'],
            'Push' => $Push, //推送商品
            'CartState' => $conf['CartState'],
            'label' => $Res['label'],
            'User' => ($User == false && $conf['ForcedLanding'] == 3 ? -1 : 1),
            'repetition' => $RS,
        ];

        HomecachingAdd($_QET['act'], [$_QET['gid']], $Data);

        Hook::execute('OrderDetails', [
            'gid' => (int)$Res['gid'],
            'uid' => ($User == false ? -1 : $User['id']),
        ]);

        dier([
            'code' => 1,
            'msg' => '商品详情获取成功',
            'data' => $Data
        ]);
        break;
    case 'CouponGet': //领取优惠券
        test(['token|e'], '请提交优惠券识别码');
        if ($User == false) {
            dies(-2, '请先完成登录！');
        }
        $Coupon = $DB->get('coupon', '*', [
            'limit_token' => $_QET['token'],
            'oid' => -1,
            'uid' => -1,
            'get_way[!]' => 1
        ]);

        if (!$Coupon) {
            dies(-1, '优惠券不足，已被领取完');
        }

        $Count = $DB->count('coupon', [
            'limit_token' => $_QET['token'],
            'uid' => $User['id'],
        ]);

        if ($Count >= $Coupon['limit']) {
            dies(-1, '此批优惠券每个用户最多领取' . $Coupon['limit'] . '张，无法继续领取！');
        }

        $CSQL = [
            'uid' => $User['id'],
            'gettime[>]' => $times,
        ];
        if ($conf['CouponUseIpType'] == 1) {
            $CSQL = [
                'OR' => [
                    'uid' => $User['id'],
                    'ip' => userip()
                ],
                'gettime[>]' => $times,
            ];
        }

        $CountUser = $DB->count('coupon', $CSQL);

        if ($CountUser >= $conf['CouponGetMax']) {
            dies(-1, '今日最多可领取' . $conf['CouponGetMax'] . '张优惠券,您已经领取了' . $CountUser . '张,请改日再来');
        }


        $Res = $DB->update('coupon', [
            'uid' => $User['id'],
            'gettime' => $date,
            'ip' => userip()
        ], [
            'id' => $Coupon['id'],
        ]);
        if ($Res) {
            userlog('领取优惠券', '用户[' . $User['id'] . ']于' . $date . '领取了优惠券[' . $Coupon['token'] . ']', $User['id'], '0');
            dies(1, '领取成功');
        } else {
            dies(-1, '领取失败!');
        }
        break;
    case 'CouponList': //取出优惠券列表
        test(['type|e'], '请选择需要获取的类别');

        $SQL = [
            'GROUP' => [
                'limit_token',
            ],
            'oid' => -1,
            'get_way[!]' => 1,
        ];

        if ($_QET['type'] == 1) {
            test(['gid|e'], '请提交需要获取的商品id');
            $SQL['gid'] = $_QET['gid'];
            $SQL['get_way'] = 2;
        } else if ($_QET['type'] == 2) {
            test(['cid|e'], '请提交需要获取的分类id');
            $SQL['cid'] = $_QET['cid'];
            $SQL['get_way'] = 3;
        } else {
            $SQL['get_way'] = 4;
        }

        if ($User == false) {
            $SQL['uid'] = -1;
        } else {
            $SQL['uid'] = [$User['id'], -1];
        }

        $Coupon = $DB->select('coupon', ['name', 'content', 'limit_token', 'money', 'minimum', 'type', 'apply', 'term_type', 'expirydate', 'indate', 'gid', 'cid'], $SQL);
        $Data = [];
        foreach ($Coupon as $v) {
            if ($User != false) {
                $v['count'] = $DB->count('coupon', [
                    'limit_token' => $v['limit_token'],
                    'uid' => $User['id'],
                    'get_way[!]' => 1,
                    'oid' => -1,
                ]);
            } else {
                $v['count'] = 0;
            }
            if ($v['term_type'] == 2 && time() > strtotime($v['expirydate'])) {
                continue;
            }
            $Type = 1;
            switch ($v['apply']) {
                case 1:
                    $Name = $DB->get('goods', ['name'], ['gid' => $v['gid']]);
                    if (!$Name) $Type = 2;
                    $scope = '此优惠券可以在购买商品[' . $Name['name'] . ']时使用！';
                    break;
                case 2:
                    $Name = $DB->get('class', ['name'], ['cid' => $v['cid']]);
                    if (!$Name) $Type = 2;
                    $scope = '此优惠券可以在分类[' . $Name['name'] . ']下的任意商品时使用！';
                    break;
                case 3:
                    $scope = '此优惠券可以在购买任意商品时使用！';
                    break;
            }
            if ($Type == 2) continue;
            if ($v['term_type'] == 2) {
                $v['expirydate'] = explode(' ', $v['expirydate'])[0];
            }
            $v['scope'] = $scope;
            $Data[] = $v;
        }

        if (count($Data) >= 1) {
            dier([
                'code' => 1,
                'msg' => '共有' . count($Data) . '个可领取优惠券！',
                'data' => $Data,
                'type' => ($User == false ? -1 : 1),
            ]);
        } else {
            dies(-3, '一张可用优惠券都没有哦');
        }
        break;
    case 'PriceCalculation': //商品售价计算！
        test(['gid|e', 'num|e']);
        if ($_QET['num'] < 1) {
            $num = 1;
        } else {
            $num = (int)$_QET['num'];
        }
        $Gid = (int)$_QET['gid'];
        $Sku = json_decode($_GET['Sku'], true);
        unset($_QET['gid'], $_QET['num'], $_QET['act'], $_QET['Sku']);
        $Res = Order::PriceCalculation($Gid, $num, $_QET, $Sku);
        dier($Res);
        break;
    case 'CreateOrder': //验证商品订单

        if ($User == false && $conf['ForcedLanding'] == 3) {
            dies(-3, '您必须先登陆用户中心才可购买商品，点击确定登陆！');
        }

        test(['gid|e', 'num|e']);
        $Gid = (int)$_QET['gid'];
        $Num = (int)$_QET['num'];
        unset($_QET['gid'], $_QET['num'], $_QET['act']);
        $Goods = Order::VerifyBuy($Gid, $Num, $_QET, $User);

        if ($Goods['freight'] <> -1) {
            $Fre = $DB->get('freight', '*', [
                'id' => $Goods['freight'],
                'LIMIT' => 1,
            ]);
            if ($Fre) {
                $price = \price::freight($Fre, $_QET, $Goods['price'], $Goods['num']);
            } else {
                $price = $Goods['price'] * $Goods['num'];
            }
        } else {
            $price = $Goods['price'] * $Goods['num'];
        }

        $Goods['method'] = json_decode($Goods['method']);
        if (in_array(2, $Goods['method']) && in_array(3, $Goods['method'])) {
            //支持余额+积分
            $Goods['method'] = 1;
        } elseif (in_array(2, $Goods['method']) && !in_array(3, $Goods['method'])) {
            //支持余额不支持积分
            $Goods['method'] = 2;
        } elseif (!in_array(2, $Goods['method']) && in_array(3, $Goods['method'])) {
            //不支持余额支持积分
            $Goods['method'] = 3;
        } else {
            //其他
            $Goods['method'] = 2;
        }

        $Input = [];
        foreach (explode('|', $Goods['value']) as $value) {
            if (strstr($value, '{') && strstr($value, '}')) {
                $Input[] = explode('{', $value)[0];
            } else {
                $Input[] = $value;
            }
        }

        if ($Goods['specification'] == 2) {
            $SpRule = RlueAnalysis($Goods['specification_set'], $Goods, 3, false);
            if ($SpRule != -1) {
                $Input = array_merge($SpRule['MasterRule'], $Input);
            }
        }

        if ($User == false) {
            $price = round($price, 2);
            $Coupon = [];
            $CouponOff = [];
        } else {
            $CouponList = $DB->select('coupon', '*', [
                'OR' => [
                    'apply' => 3,
                    'gid' => $Goods['gid'],
                    'cid' => $Goods['cid'],
                ],
                'oid' => -1,
                'uid' => $User['id'],
            ]);

            $Coupon = [];
            $CouponOff = [];

            foreach ($CouponList as $v) {
                $Types = 1;
                switch ($v['apply']) {
                    case 1:
                        if ($Goods['gid'] != $v['gid']) {
                            $Types = 2;
                        }
                        break;
                    case 2:
                        if ($Goods['cid'] != $v['cid']) {
                            $Types = 2;
                        }
                        break;
                }

                if ($v['term_type'] == 1) {
                    $TIME = strtotime($v['gettime']) + (60 * 60 * 24 * $v['indate']);
                } else {
                    $TIME = strtotime($v['expirydate']);
                }

                if (time() > $TIME) {
                    $Types = 2;
                }

                if ($Types == 2) {
                    continue;
                }

                switch ($v['type']) {
                    case 1:
                        if ($v['minimum'] > $price) {
                            $Types = 2;
                            $explain = '订单付款金额需满' . $v['minimum'] . '元才可使用，满' . $v['minimum'] . '元可优惠' . $v['money'] . '元！';
                        } else $explain = '满' . $v['minimum'] . '元可优惠' . $v['money'] . '元！';
                        $PriceCou = $price - $v['money'];
                        $Money = '减免' . $v['money'] . '元';
                        break;
                    case 2:
                        $explain = '下单即可优惠' . $v['money'] . '元！';
                        $PriceCou = $price - $v['money'];
                        $Money = '减免' . $v['money'] . '元';
                        break;
                    case 3:
                        if ($v['minimum'] > $price) {
                            $Types = 2;
                            $explain = '订单付款金额需满' . $v['minimum'] . '元才可使用，满' . $v['minimum'] . '元可享' . $v['money'] / 10 . '折优惠！';
                        } else $explain = '满' . $v['minimum'] . '元可享' . $v['money'] / 10 . '折优惠,约减免' . round($price - $PriceCou, 2) . '元！';
                        $PriceCou = ($price * ($v['money'] / 100));
                        $Money = ($v['money'] / 10) . '折购';
                        break;
                }

                $CSQL = [
                    'uid' => $User['id'],
                    'oid[!]' => -1,
                    'endtime[>]' => $times
                ];
                if ($conf['CouponUseIpType'] == 1) {
                    $CSQL = [
                        'OR' => [
                            'uid' => $User['id'],
                            'ip' => userip(),
                        ],
                        'oid[!]' => -1,
                        'endtime[>]' => $times
                    ];
                }
                $Count = $DB->count('coupon', $CSQL);
                if ($Count >= $conf['CouponUsableMax']) {
                    $explain = '每天最多可使用' . $conf['CouponUsableMax'] . '张优惠券,今日已经使用了' . $Count . '张！';
                    $Types = 2;
                }

                if ($Types == 2) {
                    $CouponOff[] =  [
                        'id' => $v['id'],
                        'name' => $v['name'],
                        'content' => $v['content'],
                        'explain' => $explain,
                        'ExpirationDate' => date("Y-m-d H:i:s", $TIME),
                        'Time' => Sec2Time($TIME - time()),
                        'Money' => $Money,
                        'type' => $v['type'],
                        'minimum' => $v['minimum'],
                        'derate' => $v['money'],
                    ];
                } else {
                    if ($conf['CouponMinimumType'] == 1) {
                        if ($PriceCou <= ($Goods['money'] * $Goods['num'])) {
                            $PriceCou = ($Goods['money'] * $Goods['num']);
                        }
                    } else {
                        if ($PriceCou <= 0) {
                            $PriceCou = 0;
                        }
                    }
                    $Coupon[] =  [
                        'id' => $v['id'],
                        'name' => $v['name'],
                        'content' => $v['content'],
                        'explain' => $explain,
                        'ExpirationTime' => date("Y-m-d H:i:s", $TIME),
                        'ExpirationDate' => Sec2Time($TIME - time()),
                        'Price' => round($PriceCou, 2),
                        'Money' => $Money,
                        'type' => $v['type'],
                        'minimum' => $v['minimum'],
                        'derate' => $v['money'],
                    ];
                }
            }

            $price = round($price, 2);
        }

        if (count($Coupon) >= 2) {
            $Coupon = array_sort($Coupon, 'Price');
        } //给出最佳优惠

        /**
         * 返回，商品价格，商品名称，下单信息，下单填写框，商品参数,购买数量，可用优惠券+不可用优惠券
         */

        dier([
            'code' => 1,
            'msg' => '商品订单信息获取成功',
            'data' => [
                'gid' => $Gid,
                'num' => $Goods['num'],
                'name' => $Goods['name'],
                'quantity' => $Goods['quantity'] * $Goods['num'],
                'data' => $_QET,
                'price' => $price,
                'points' => round($Goods['points'] * $Goods['num'], 0),
                'type' => 1,
                'method' => $Goods['method'],
                'currency' => $conf['currency'],
                'input' => $Input
            ],
            'Coupon' => $Coupon,
            'CouponOff' => $CouponOff,
        ]);
        break;
    case 'PaymentWay': //获取支付通道状态
        test(['gid|i', 'type|i']);

        switch ($_QET['type']) {
            case 1: //普通付款订单

                $Goods = $DB->get('goods', [
                    'method', 'cid', 'gid'
                ], [
                    'gid' => $_QET['gid'],
                    'state' => 1
                ]);

                if (!$Goods) {
                    dies(-1, '商品不存在,或已下架,无法进行购买！');
                }

                $Class = $DB->get('class', ['support'], [
                    'cid' => $Goods['cid']
                ]);

                $Meth = json_decode($Goods['method']);
                if (in_array(2, $Meth) && in_array(3, $Meth)) {
                    //支持余额+积分
                    $Goods['method'] = 1;
                } elseif (in_array(2, $Meth) && !in_array(3, $Meth)) {
                    //支持余额不支持积分
                    $Goods['method'] = 2;
                } elseif (!in_array(2, $Meth) && in_array(3, $Meth)) {
                    //不支持余额支持积分
                    $Goods['method'] = 3;
                } else {
                    //其他
                    $Goods['method'] = 2;
                }
                if ($Class) {
                    $support = explode(',', $Class['support']);
                    $Data = [[
                        'type' => ($conf['PayConQQ'] == -1 || $support[0] != 1 || !in_array(1, $Meth) ? 2 : 1), //QQ
                    ], [
                        'type' => ($conf['PayConWX'] == -1 || $support[1] != 1 || !in_array(1, $Meth) ? 2 : 1), //微信
                    ], [
                        'type' => ($conf['PayConZFB'] == -1 || $support[2] != 1 || !in_array(1, $Meth) ? 2 : 1), //支付宝
                    ], [
                        'type' => ($support[3] != 1 || $Goods['method'] == 3 ? 2 : 1),
                        'surplus' => ($User == false ? '未登陆，点击登陆' : '当前余额：' . $User['money'])
                    ], [
                        'type' => ($support[4] != 1 || $Goods['method'] == 2 ? 2 : 1),
                        'surplus' => ($User == false ? '未登陆，点击登陆' : '当前' . $conf['currency'] . '：' . $User['currency'])
                    ]];
                } else {
                    $Data = [[
                        'type' => ($conf['PayConQQ'] == -1 || !in_array(1, $Meth) ? 2 : 1), //QQ
                    ], [
                        'type' => ($conf['PayConWX'] == -1 || !in_array(1, $Meth) ? 2 : 1), //微信
                    ], [
                        'type' => ($conf['PayConZFB'] == -1 || !in_array(1, $Meth) ? 2 : 1), //支付宝
                    ], [
                        'type' => ($Goods['method'] == 3 ? 2 : 1),
                        'surplus' => ($User == false ? '未登陆，点击登陆' : '当前余额：' . $User['money'])
                    ], [
                        'type' => ($Goods['method'] == 2 ? 2 : 1),
                        'surplus' => ($User == false ? '未登陆，点击登陆' : '当前' . $conf['currency'] . '：' . $User['currency'])
                    ]];
                }

                Hook::execute('GoodsDetails', [
                    'gid' => $_QET['gid'],
                    'uid' => ($User == false ? -1 : $User['id'])
                ]);

                dier([
                    'code' => 1,
                    'msg' => '数据获取成功',
                    'data' => $Data,
                    'state' => ($User == false ? 2 : 1)
                ]);
                break;
            case 2: //购物车
                $Arr = explode(',', $conf['CartPaySet']);
                $Data = [[
                    'type' => ($conf['PayConQQ'] == -1 || !in_array(3, $Arr) ? 2 : 1), //QQ
                ], [
                    'type' => ($conf['PayConWX'] == -1 || !in_array(2, $Arr) ? 2 : 1), //微信
                ], [
                    'type' => ($conf['PayConZFB'] == -1 || !in_array(1, $Arr) ? 2 : 1), //支付宝
                ], [
                    'type' => (!in_array(4, $Arr) ? 2 : 1),
                    'surplus' => ($User == false ? '未登陆，点击登陆' : '当前余额：' . $User['money'])
                ], [
                    'type' => (!in_array(5, $Arr) ? 2 : 1),
                    'surplus' => ($User == false ? '未登陆，点击登陆' : '当前' . $conf['currency'] . '：' . $User['currency'])
                ]];

                dier([
                    'code' => 1,
                    'msg' => '数据获取成功',
                    'data' => $Data,
                    'state' => ($User == false ? 2 : 1),
                    'notice' => html_entity_decode($conf['CartNotice']),
                    'currency' => $conf['currency']
                ]);
                break;
        }

        break;
    case 'Pay': //开始支付
        test(['gid|e', 'num|e', 'type|e', 'mode|e']);
        $gid = (int)$_QET['gid'];
        $num = (int)$_QET['num'];
        $type = (int)$_QET['type'];
        $mode = $_QET['mode'];
        $CouponId = (empty($_QET['CouponSelect']) ? -1 : $_QET['CouponSelect']);
        unset($_QET['gid'], $_QET['num'], $_QET['type'], $_QET['act'], $_QET['mode'], $_QET['CouponSelect']);

        foreach ($_QET as $value) {
            if (empty($value)) {
                dies(-1, '请填写完整！');
            }
        }

        $order = Order::Creation([
            'gid' => $gid,
            'num' => $num,
            'data' => $_QET,
            'type' => $type,
            'mode' => $mode,
            'CouponId' => ($User == false ? -1 : $CouponId)
        ], $User);

        if ($order <> false) {
            OrderStatus($order);
        } else {
            dies(-1, '订单创建失败,请联系管理员处理！');
        }

        break;
    case 'Discuss': //评论列表
        test(['gid|e', 'num|e']);

        $Data = HomecachingVerify($_QET['act'], [$_QET['gid'], $_QET['num']]);
        if ($Data == false) {
            $Res = $DB->select('mark', [
                '[>]user' => ['uid' => 'id']
            ], [
                'mark.id',
                'user.image',
                'user.name(username)',
                'mark.content',
                'mark.image(imageArr)',
                'mark.score',
                'mark.name(goodsname)'
            ], ['mark.gid' => $_QET['gid'], 'mark.state' => 1, 'LIMIT' => (int)$_QET['num'], 'ORDER' => [
                'id' => 'DESC'
            ]]);

            $Data = [];
            foreach ($Res as $v) {
                if (!empty($v['imageArr'])) {
                    $is = explode('|', $v['imageArr']);
                    $d = [];

                    foreach ($is as $vs) {
                        $d[] = ImageUrl($vs);
                    }
                    $v['imageArr'] = $d;
                } else {
                    $v['imageArr'] = [];
                }

                $Data[] = $v;
            }

            HomecachingAdd($_QET['act'], [$_QET['gid'], $_QET['num']], $Data);
        }

        $Avg = $DB->avg('mark', 'score', ['gid' => $_QET['gid'], 'state' => 1]);

        dier([
            'code' => 1,
            'msg' => '评论列表获取成功',
            'data' => $Data,
            'count' => (int)$DB->count('mark', [
                'gid' => $_QET['gid'],
                'state' => 1
            ]),
            'avg' => (int)$Avg
        ]);
        break;
    case 'GuessYouLike': //推荐商品
        test(['gid|e', 'page|e']);

        if ($conf['GoodsRecommendation'] != 1) {
            dies(-2, '商品推荐已关闭！');
        }
        $GoodsHide = UserConf::GoodsHide();

        $Data = HomecachingVerify($_QET['act'], [$_QET['gid'], $_QET['page']]);

        Hook::execute('GuessYouLike', [
            'gid' => $_QET['gid'],
            'page' => $_QET['page']
        ]);

        $SQL = '';
        if (count($GoodsHide) >= 1) {
            foreach ($GoodsHide as $value) {
                $SQL .= " AND  gid <> " . (int)$value . " ";
            }
        }

        if ($Data == false) {
            $LIMIT = (empty($conf['HomeLimit']) ? 6 : $conf['HomeLimit']);
            $Page = ($_QET['page'] - 1) * $LIMIT;
            $Res = $DB->query("SELECT gid,cid,name,image,money,profits,custom,freight,method,quantity,quota,sqid,specification_set,specification_sku,specification,label,(SELECT count(b.gid) FROM `sky_order` as b WHERE b.gid = a.gid LIMIT 188 ) as cgid FROM `sky_goods` as a WHERE `gid` >= (SELECT floor(RAND() * (SELECT MAX(gid) FROM `sky_goods` WHERE `state` = 1 ))) AND `state` = 1 AND `gid` <> " . (int)$_QET['gid'] . " " . $SQL . " ORDER BY cgid DESC  LIMIT " . $Page . " , " . $LIMIT . " ");
            $Data = [];
            foreach ($Res as $res) {
                if ($res['specification'] == 2) {
                    $SpRule = RlueAnalysis($res['specification_set'], $res, 1, true);
                    if ($SpRule == -1) {
                        $res['DataRule'] = -1;
                        $price = price::price_uid(($User == false ? -1 : $User['grade']), $res['profits'], $res['money'], $res['custom'], UserConf::GoodsPrice($res['gid']));
                        $Coun = $DB->sum('buylog', 'num', [
                            'gid' => $res['gid'],
                            'date[>]' => $times
                        ]);
                        $res['quota'] = $res['quota'] - $Coun;
                        $res['level'] = $price['level'];
                    } else {
                        $SkuData = [
                            'data' => $SpRule,
                        ];
                        $DataRule = $SkuData['data']['Parameter'][$Index];
                        $res['quantity'] = $SkuData['data']['Quantity']['max'];
                        $res['quota'] = $SkuData['data']['Inventory']['max'];
                        $res['level'] = $SkuData['data']['level'];
                        $price = [
                            'price' => $SkuData['data']['Price']['min'],
                            'points' => $SkuData['data']['Points']['min'],
                            'level' => $DataRule['level'],
                        ];
                        $res['DataRule'] = [
                            'Price' => $SkuData['data']['Price'],
                            'Points' => $SkuData['data']['Points'],
                            'Inventory' => $SkuData['data']['Inventory'],
                            'Quantity' => $SkuData['data']['Quantity'],
                        ];
                    }
                } else {
                    $res['DataRule'] = -1;
                    $price = price::price_uid(($User == false ? -1 : $User['grade']), $res['profits'], $res['money'], $res['custom'], UserConf::GoodsPrice($res['gid']));
                    $Coun = $DB->sum('buylog', 'num', [
                        'gid' => $res['gid'],
                        'date[>]' => $times
                    ]);
                    $res['quota'] = $res['quota'] - $Coun;
                    $res['level'] = $price['level'];
                }

                if ($res['sqid'] == -3) {
                    //获取卡密库存
                    $res['quota'] = $DB->count('token', [
                        "AND" => [
                            "OR" => [
                                "order[=]" => "",
                                "order" => null
                            ],
                            "gid" => $res['gid']
                        ],
                    ]);
                }

                $res['method'] = json_decode($res['method'], true);

                if (in_array(2, $res['method']) && in_array(3, $res['method'])) {
                    //支持余额+积分
                    $res['method'] = 1;
                } elseif (in_array(2, $res['method']) && !in_array(3, $res['method'])) {
                    //支持余额不支持积分
                    $res['method'] = 2;
                } elseif (!in_array(2, $res['method']) && in_array(3, $res['method'])) {
                    //不支持余额支持积分
                    $res['method'] = 3;
                } else {
                    //其他
                    $res['method'] = 2;
                }

                if ($price['price'] <= 0.01 && $price['price'] <> 0) {
                    $price['price'] = 0.01;
                }
                $res['price'] = round($price['price'], 2);
                $res['points'] = round($price['points'], 0);
                $res['level'] = $price['level'];

                switch ($res['sqid']) {
                    case -1: //自营
                        $res['state'] = 1;
                        break;
                    case -2: //API
                        $res['state'] = 2;
                        break;
                    case -3: //发卡
                        $res['state'] = 3;
                        break;
                    default: //对接
                        $res['state'] = 4;
                        break;
                }

                $res['currency'] = $conf['currency'];

                unset($res['profits'], $res['money'], $res['sqid'], $res['specification_set'], $res['specification_sku'], $res['custom']);


                $res['image'] = ImageUrl($res['image']);

                if (empty($_SESSION['GIDSALES_' . $res['gid']])) {
                    $LSALES = $conf['SalesSum'] + round(($conf['SalesSum'] * (rand(1, 50) / 100)), 0);
                    $_SESSION['GIDSALES_' . $res['gid']] = $LSALES;
                } else {
                    $LSALES = $_SESSION['GIDSALES_' . $res['gid']];
                }

                $res['sales'] = $res['cgid'] + $LSALES; //商品销量
                unset($res['cgid']);

                if ($res['label'] == '') {
                    $res['label'] = explode('|', $conf['DefaultLabel']);
                } else {
                    $res['label'] = explode('|', $res['label']);
                    if (count($res['label']) == 0) {
                        $res['label'] = explode('|', $conf['DefaultLabel']);
                    }
                }

                if (count($res['label']) == 0) {
                    $res['label'] = ['官方'];
                }
                $Label = [];
                foreach ($res['label'] as $v) {
                    $v = explode(',', $v);
                    $Label[] = [
                        'name' => $v[0],
                        'color' => (empty($v[1]) ? 'red' : $v[1])
                    ];
                }
                $res['label'] = $Label;

                $Data[] = $res;
            }
        }

        dier([
            'code' => 1,
            'msg' => '推荐商品列表获取成功！',
            'data' => $Data,
        ]);
        break;
    case 'OrdeTips': //新订单通知，动态通知

        if ($conf['DynamicMessage'] != 1) {
            dies(-2, '动态通知已经关闭');
        }

        $SQL = [
            'ORDER' => [
                'order.addtitm' => 'DESC'
            ],
            'LIMIT' => 30
        ];

        if (!empty($_QET['gid'])) {
            $SQL = array_merge($SQL, [
                'order.gid' => $_QET['gid']
            ]);
        }

        $Res = $DB->select('order', [
            '[>]goods' => ['gid' => 'gid'],
            '[>]user' => ['uid' => 'id']
        ], [
            'order.addtitm',
            'goods.name(title)',
            'user.name',
            'user.image'
        ], $SQL);

        $Data = [];
        foreach ($Res as $v) {
            $Data[] = [
                'title' => ($v['name'] == '' ? '游客' : $v['name']) . '于' . TimeLag($v['addtitm']) . '前购买了' . (!empty($_QET['gid']) ? '此商品' : $v['title']),
                'img' => ($v['image'] == '' ? 'https://api.ixiaowai.cn/mcapi/mcapi.php?t=' . $v['id'] : $v['image']),
            ];
        }

        if (count($Data) < 30) {
            $SQL2 = [
                'mark.state' => 1,
                'LIMIT' => 30,
                'ORDER' => [
                    'mark.addtime' => 'DESC'
                ],
            ];

            if (!empty($_QET['gid'])) {
                $SQL2 = array_merge($SQL2, [
                    'mark.gid' => $_QET['gid']
                ]);
            }

            $Res = $DB->select('mark', [
                '[>]user' => ['uid' => 'id']
            ], [
                'mark.name(title)',
                'user.name',
                'user.image',
                'user.uid',
                'mark.addtime',
                'mark.score'
            ], $SQL2);

            foreach ($Res as $v) {
                if (empty($_QET['gid'])) {
                    $msg = ($v['name'] == '' ? '用户' . $v['uid'] : $v['name']) . '于' . TimeLag($v['addtime']) . '前评论了' . (!empty($_QET['gid']) ? '此商品' : $v['title']);
                } else {
                    $msg = ($v['name'] == '' ? '用户' . $v['uid'] : $v['name']) . TimeLag($v['addtime']) . '前给出了' . $v['score'] . '星评价！';
                }
                $Data[] = [
                    'title' => $msg,
                    'img' => ($v['image'] == '' ? 'https://api.ixiaowai.cn/mcapi/mcapi.php?t=' . $v['id'] : $v['image']),
                ];
            }
        }

        if (count($Data) < 60) {
            $SQL3 = [
                'LIMIT' => 30,
                'ORDER' => [
                    'journal.date' => 'DESC'
                ],
                'journal.name' => '每日签到'
            ];

            $Res = $DB->select('journal', [
                '[>]user' => ['uid' => 'id']
            ], [
                'user.name',
                'user.image',
                'journal.date'
            ], $SQL3);

            foreach ($Res as $v) {
                $Data[] = [
                    'title' => ($v['name'] == '' ? '用户' : $v['name']) . '于' . TimeLag($v['date']) . '前签到成功！',
                    'img' => ($v['image'] == '' ? 'https://api.ixiaowai.cn/mcapi/mcapi.php?t=' . $v['id'] : $v['image']),
                ];
            }
        }

        dier([
            'code' => 1,
            'msg' => '数据获取成功',
            'data' => $Data
        ]);
        break;
    case 'GoodsMonitoring': //商品价格监控
        test(['gid|e']);
        $gid = (int)$_QET['gid'];
        $Goods = $DB->get('goods', '*', [
            'gid' => $gid
        ]);
        if (!$Goods) {
            dies(-2, '商品不存在！');
        }
        if (in_array(5, json_decode($Goods['method'], true))) {
            $Flie = ROOT . 'includes/lib/soft/controller/CommodityPriceMonitoring/index.php';
            if (!file_exists($Flie)) {
                dies(1, '应用未安装！');
            }
            include_once $Flie;
            $DB = new DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
            $state_gid = \lib\CommodityPriceMonitoring::origin($Goods);
            if ($state_gid == -1) {
                $user_data = login_data::user_data();
                HomecachingUnlink('Goods', [$_QET['gid']]);
                dies(-1, $conf['SupervisoryMsg']);
            } else {
                dies(1, '商品价格无需调整！');
            }
        }
        break;
    case 'SharePoster': //商品海报图分享
        test(['gid|e']);

        Hook::execute('SharePoster', [
            'gid' => $_QET['gid']
        ]);

        $Data = HomecachingVerify('SharePoster', [$_QET['gid']]);
        if ($Data == false) {
            include_once(SYSTEM_ROOT . "extend/GoodsImage.php");
            $image = ($conf['share_image'] == 1 ? GoodsImage::mergePic($_QET['gid']) : GoodsImage::mergPicClouds($_QET['gid']));
            if ($image) {
                $Data = [
                    'code' => 1,
                    'msg' => '商品海报图生成成功！',
                    'src' => ImageUrl($image) . '?sr=' . time()
                ];
                HomecachingAdd('SharePoster', [$_QET['gid']], $Data);
                dier($Data);
            } else {
                dies(-1, '商品海报图生成失败！');
            }
        } else {
            dier($Data);
        }
        break;
    case 'OrderState': //查询支付状态，公共查询模块，和支付调用相互独立
        test(['pid|e', 'type|e']);
        $Pay = $DB->get(($_QET['type'] == 1 ? 'pay' : 'order'), '*', [
            'id' => (int)$_QET['pid']
        ]);

        if (!$Pay) {
            dies(-3, '订单不存在,或未提交！');
        }

        if ($Pay['state'] == 1 || $_QET['type'] == 2) {
            switch ($Pay['gid']) {
                case -1: //在线充值
                    dies(1, '恭喜您成功充值' . round($Pay['money'], 2) . '元！');
                    break;
                case -2: //订单队列
                    dies(1, '恭喜您成功购买' . $Pay['name'] . '！');
                    break;
                default: //普通付款订单
                    OrderStatus($Pay['trade_no'], 2);
                    break;
            }
        } else {
            dies(-2, '支付订单未完成！');
        }
        break;
    case 'SubmitOrder': //提交队列订单到服务器
        dier(Order::SubmitOrderQueue((empty($_QET['id']) ? false : $_QET['id']), 2));
        break;
    case 'OrderPay': //队列订单付款！
        test(['id|e']);
        query::OrderPay($_QET['id']);
        break;
    case 'OrderList': //取出订单列表
        test(['type|e']);
        switch ($_QET['type']) {
            case 'OrderAll':
                \query::OrderAll($_QET['id'], $_QET['seek'], $_QET['state'], $_QET['page'], $User);
                break;
            case 'QueryList': //查询未绑定订单
                \query::QueryList($_QET['msg']);
                break;
            case 'QueryMark': //提交商品评价内容
                \query::QueryMark($_QET, $User);
                break;
            case 'QueryTake': //确认收货
                \query::QueryTake($_QET['id'], $User);
                break;
            case 'QueryDelete': //删除待付款队列订单
                \query::QueryDelete($_QET['id'], $User);
                break;
            case 'QueryDetails': //查询订单进度
                dier(Order::Query($_QET['id'], ($User == false ? false : $User['id'])));
                break;
            case 'Queue': //查询队列内的订单，未完成+待付款
                \query::QueueList($User);
                break;
        }
        break;
    case 'CartAdd': //加入购物车

        if ($User == false && $conf['ForcedLanding'] == 3) {
            dies(-3, '您必须先登陆用户中心才可以将商品加入购物车，点击确定登陆！');
        }

        if ($conf['CartState'] <> 1) {
            dies(-1, '购物车功能已经关闭!');
        }
        test(['gid|e', 'num|e']);
        $Gid = (int)$_QET['gid'];
        $Num = (int)$_QET['num'];
        unset($_QET['gid'], $_QET['num'], $_QET['act']);
        foreach ($_QET as $value) {
            if (empty($value)) {
                dies(-1, '请填写完整！');
            }
        }
        \extend\GoodsCart::CartAdd([
            'gid' => $Gid,
            'num' => $Num,
            'data' => $_QET
        ]);
        break;
    case 'CartNum': //购物车下单份数修改
        \extend\GoodsCart::CartNum($_QET);
        break;
    case 'CartList': //查询购物车列表
        if (isset($_QET['data'])) {
            $_QET['data'] = explode(',', $_QET['data']);
        }
        dier(\extend\GoodsCart::CartList($_QET['data'], $_QET['CartKey'], $User));
        break;
    case 'CartDet': //删除购物车指定内容
        test(['arr|i']);
        if (\extend\GoodsCart::CartDet(explode(',', $_QET['arr']), 2) == true) {
            dies(1, '删除成功！');
        } else {
            dies(-1, '删除失败！');
        }
        break;
    case 'CartPay': //结算购物车商品
        test(['type|e', 'mode|e']);
        $type = (int)$_QET['type'];
        $mode = $_QET['mode'];
        unset($_QET['type'], $_QET['act'], $_QET['mode'], $_QET['currency']);
        if (count($_QET) == 0) {
            dies(-1, '请将需要支付的订单填写完整哦');
        }
        \extend\GoodsCart::CartPay($_QET, $type, $mode, $_QET['CartKey']);
        break;
    default:
        header('HTTP/1.1 404 Not Found');
        dies(-2, '访问路径不存在！');
        break;
}
